package com.github.baichuan.iot.gateway.jt808.handler;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufUtil;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;
import lombok.extern.slf4j.Slf4j;

import java.util.List;

/**
 * 粘包消息分割器
 */
@ChannelHandler.Sharable
@Slf4j
public class MessageSplitter extends ByteToMessageDecoder {
    @Override
    protected void decode(ChannelHandlerContext context, ByteBuf buf, List<Object> out) throws Exception {
        byte[] word = new byte[2];

        while(true) {
            if(buf.readableBytes() < 16) {
                //剩余包长度不足
                return;
            }

            buf.markReaderIndex();

            short delimiter = buf.readUnsignedByte();
            if(delimiter != 0x7E) {
                //包头错误
                log.info("Illegal inbound data {}", ByteBufUtil.hexDump(buf));
                buf.clear();
                return;
            }

            buf.skipBytes(2);
            // 消息体属性
            buf.readBytes(word);
            int payloadLength = ((word[1] & 0x01) << 8) + (word[0] & 0xFF);
            int messageLength = 1 + 16 + payloadLength + 1 + 1;
            buf.resetReaderIndex();

            if(buf.readableBytes() < messageLength) {
                return;
            }

        }


    }
}
